package com.team.merchant.controller;

import com.team.common.core.web.domain.AjaxResult;
import com.team.merchant.domain.vo.RabbitDetailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test/redis")
@Slf4j
public class TestRedisController {

    // Redis Key常量
    private static final String GLOBAL_STATS_KEY = "stats:summary";
    private static final String ORDER_BY_TYPE_KEY = "stats:orders_by_type";
    private static final String REVENUE_PREFIX = "stats:revenue:";
    private static final String LEADERBOARD_KEY = "stats:leaderboard";
    
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/status")
    public AjaxResult testRedisStatus() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 测试Redis连接
            boolean connectionStatus = !redisTemplate.getConnectionFactory().getConnection().isClosed();
            result.put("connectionStatus", connectionStatus ? "正常" : "已关闭");
            
            // 测试简单操作
            redisTemplate.opsForValue().set("test:key", "test-value");
            String value = redisTemplate.opsForValue().get("test:key");
            result.put("simpleOperationTest", value != null && value.equals("test-value"));
            
            return AjaxResult.success("Redis连接测试完成", result);
        } catch (Exception e) {
            log.error("Redis测试失败: {}", e.getMessage(), e);
            result.put("error", e.getMessage());
            return AjaxResult.error("Redis连接测试失败", result);
        }
    }
    
    @GetMapping("/simulate")
    public AjaxResult simulateOrderMessage() {
        try {
            // 创建模拟消息
            RabbitDetailVo rabbitDetailVo = new RabbitDetailVo();
            rabbitDetailVo.setOrderId(1000L);
            rabbitDetailVo.setServiceType("maintenance");
            rabbitDetailVo.setAmount(100.0);
            rabbitDetailVo.setOperation("测试");
            rabbitDetailVo.setTimestamp(new Date());
            
            log.info("模拟消息: {}", rabbitDetailVo);
            
            // 数据准备
            String serviceType = rabbitDetailVo.getServiceType();
            long amountInCents = (long) (rabbitDetailVo.getAmount() * 100);
            
            // 执行Redis事务操作
            Object result = redisTemplate.execute(new SessionCallback<Object>() {
                @Override
                public Object execute(RedisOperations operations) {
                    operations.multi();  // 开启事务

                    // 更新全局统计
                    operations.opsForHash().increment(GLOBAL_STATS_KEY, "total_orders", 1);
                    operations.opsForHash().increment(GLOBAL_STATS_KEY, "total_revenue", amountInCents);

                    // 更新分类订单量（Sorted Set）
                    operations.opsForZSet().incrementScore(ORDER_BY_TYPE_KEY, serviceType, 1);

                    // 更新分类收入（String）
                    String revenueKey = REVENUE_PREFIX + serviceType;
                    operations.opsForValue().increment(revenueKey, amountInCents);

                    // 更新收入排行榜（Sorted Set）
                    operations.opsForZSet().incrementScore(LEADERBOARD_KEY, serviceType, amountInCents);

                    return operations.exec();  // 提交事务
                }
            });
            
            // 查询更新后的数据
            Map<String, Object> data = new HashMap<>();
            data.put("transactionResult", result);
            data.put("totalOrders", redisTemplate.opsForHash().get(GLOBAL_STATS_KEY, "total_orders"));
            data.put("totalRevenue", redisTemplate.opsForHash().get(GLOBAL_STATS_KEY, "total_revenue"));
            data.put("typeOrders", redisTemplate.opsForZSet().score(ORDER_BY_TYPE_KEY, serviceType));
            data.put("typeRevenue", redisTemplate.opsForValue().get(REVENUE_PREFIX + serviceType));
            data.put("leaderboardScore", redisTemplate.opsForZSet().score(LEADERBOARD_KEY, serviceType));
            
            return AjaxResult.success("模拟消息处理成功", data);
        } catch (Exception e) {
            log.error("模拟消息处理失败: {}", e.getMessage(), e);
            return AjaxResult.error("模拟消息处理失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/keys")
    public AjaxResult getRedisKeys() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取所有相关的键
            result.put("globalStatsKey", redisTemplate.hasKey(GLOBAL_STATS_KEY));
            result.put("orderByTypeKey", redisTemplate.hasKey(ORDER_BY_TYPE_KEY));
            result.put("leaderboardKey", redisTemplate.hasKey(LEADERBOARD_KEY));
            
            // 获取所有收入前缀的键
            result.put("revenueKeys", redisTemplate.keys(REVENUE_PREFIX + "*"));
            
            return AjaxResult.success("Redis键查询成功", result);
        } catch (Exception e) {
            log.error("Redis键查询失败: {}", e.getMessage(), e);
            return AjaxResult.error("Redis键查询失败: " + e.getMessage());
        }
    }
} 